import Taro from '@tarojs/taro'
import { getStorageSync } from '@/utils/storage'
import { loading, toast } from '@/utils/utils'

class Model {
  constructor () {}

  api (options = {}) {

    if (!options.method) options.method = 'get'

    return new Promise((resolve, reject) => {
      loading(true)
      Taro.request({
        method: options.method,
        url: `${process.env.BASE_URL}/api${options.url}`,
        header: {
          Authorization: getStorageSync('token')
        },
        data: {
          param: options.data || {data: {}}
        },
        success: function (res) {
          loading(false)

          let { data } = res

          if (data.success) resolve(data)
          else {
            toast(true, data.message)
            switch (Number(data.code)) {
            case 401:
              Taro.reLaunch({
                url: '/pages/login/login',
              })
              break
            }
            reject(data)
          }
        },
        fail: function (error) {
          loading(false)
          reject(error)
        },
        complete: function (res) {}
      })
    })
  }

  get (options = {}) {
    options.method = 'GET'
    return this.api(options)
  }

  post (options = {}) {
    options.method = 'POST'
    return this.api(options)
  }

  put (options = {}) {
    options.method = 'PUT'
    return this.api(options)
  }

  delete (options = {}) {
    options.method = 'DELETE'
    return this.api(options)
  }
}

export default Model
